<script setup lang="ts">
import { IconUser, IconSettings } from "@arco-design/web-vue/es/icon";
import { routes } from "@/router/routes";
import { useRouter } from "vue-router";
import { ref, computed, onMounted, watchEffect } from "vue";
import { useLoginUserStore } from "@/store/userStore";
import checkAccess from "@/access/checkAccess";
import { userLogoutUsingPost } from "@/api/userController";
import message from "@arco-design/web-vue/es/message";
import { lightTheme, darkTheme } from "@/assets/theme/themeToken";

// 用户和路由
const loginUserStore = useLoginUserStore();
const router = useRouter();

// 可见菜单项
const visibleRoutes = computed(() => {
  return routes.filter((item) => {
    if (item.meta?.hideInMenu) return false;
    return checkAccess(loginUserStore.loginUser, item.meta?.access as string);
  });
});

// 路由跳转
const selectedKeys = ref(["/"]);
const doMenuClick = (key: string) => router.push({ path: key });
router.afterEach((to) => {
  selectedKeys.value = [to.path];
});

// 登录/登出/切换
const goLogin = () => router.push({ path: "/user/login" });
const goLogout = async () => {
  const res = await userLogoutUsingPost();
  if (res.data.code === 0) {
    await router.push({ path: "/", replace: true });
    message.success("已成功退出");
    window.location.reload();
  }
};
const switchAccount = () => window.open("/user/login", "_blank");

// 用户菜单下拉状态
const dropdownVisible = ref(false);

// ===== 🎨 深色 / 浅色切换逻辑 =====
const isDark = ref(false);
const toggleTheme = () => {
  isDark.value = !isDark.value;
  const newTheme = isDark.value ? "dark" : "light";
  currentTheme.value = newTheme;
  localStorage.setItem("theme", newTheme);
};

const currentTheme = ref<"light" | "dark">("light");
const themeToken = ref(lightTheme);

// 读取本地主题
onMounted(() => {
  const savedTheme =
    (localStorage.getItem("theme") as "light" | "dark") || "light";
  currentTheme.value = savedTheme;
  themeToken.value = savedTheme === "dark" ? darkTheme : lightTheme;
  document.documentElement.setAttribute("data-theme", savedTheme);
});

// 监听变化，切换主题
watchEffect(() => {
  if (currentTheme.value === "dark") {
    themeToken.value = darkTheme;
    document.documentElement.setAttribute("data-theme", "dark");
  } else {
    themeToken.value = lightTheme;
    document.documentElement.setAttribute("data-theme", "light");
  }
});
</script>

<template>
  <a-row id="globalHeader" align="center" :wrap="false">
    <a-col flex="auto">
      <a-menu
        mode="horizontal"
        :selected-keys="selectedKeys"
        @menu-item-click="doMenuClick"
        :style="{
          backgroundColor: 'var(--bg-color)',
          color: 'var(--text-color)',
          borderBottom: '1px solid var(--border-color)',
        }"
      >
        <a-menu-item
          key="0"
          :style="{ padding: 0, marginRight: '38px' }"
          disabled
        >
          <div class="titleBar">
            <img class="logo" src="../assets/logo.png" alt="logo" />
            <div class="title">应用平台</div>
          </div>
        </a-menu-item>
        <a-menu-item v-for="item in visibleRoutes" :key="item.path">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
    </a-col>

    <a-col flex="auto" class="right-bar">
      <a-button
        shape="circle"
        size="mini"
        type="text"
        @click="toggleTheme"
        :title="isDark ? '切换为浅色模式' : '切换为深色模式'"
      >
        {{ isDark ? "☀️" : "🌙" }}
      </a-button>

      <template v-if="loginUserStore.loginUser.id">
        <div class="user-info">
          <span>{{ loginUserStore.loginUser.userName ?? "无名" }}</span>
          <a-dropdown
            v-model:popup-visible="dropdownVisible"
            position="bottom"
            trigger="click"
          >
            <a-button type="text" size="mini" @click.stop>
              <template #icon>
                <IconSettings />
              </template>
              设置
            </a-button>
            <template #content>
              <a-doption @click="switchAccount">切换账号</a-doption>
              <a-doption @click="goLogout" style="color: red"
                >退出登录
              </a-doption>
            </template>
          </a-dropdown>
        </div>
      </template>
      <template v-else>
        <a-avatar
          :trigger-icon-style="{ color: '#3491FA' }"
          :auto-fix-font-size="false"
          @click="goLogin"
          class="avatar"
          :style="{ backgroundColor: '#168CFF' }"
        >
          <IconUser />
        </a-avatar>
      </template>
    </a-col>
  </a-row>
</template>

<style scoped>
#globalHeader {
  padding: 0 16px;
  height: 64px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  background-color: var(--bg-color);
  color: var(--text-color);
}

.titleBar {
  display: flex;
  align-items: center;
}

.logo {
  height: 48px;
}

.title {
  color: var(--text-color);
  margin-left: 16px;
  font-weight: bold;
  font-size: 18px;
}

.avatar {
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-left: 16px;
}

.right-bar {
  display: flex;
  align-items: center;
  gap: 16px;
  justify-content: flex-end;
}

:deep(.arco-menu-horizontal. arco-menu-inner) {
  background-color: var(--bg-color);
  color: var(--text-color);
}

:deep(.arco-menu-horizontal .arco-menu-inner. arco-menu-item) {
  color: var(--text-color);
}

:deep(.arco-menu-horizontal. arco-menu-item. arco-menu-selected) {
  border-bottom: 2px solid #1890ff; /* 你可以自定义选中样式 */
}
</style>
